package client.profesor;

import static client.common.javascript.JsConsole.console;
import static client.common.libs.Underscore._;
import static org.stjs.javascript.JSCollections.$array;

import org.stjs.javascript.Array;
import org.stjs.javascript.Map;

import client.common.EndPoints.UserEP;
import client.common.Models.User;
import client.common.angular.EmptyPromise;
import client.common.angular.NgScope;
import client.common.angular.UIState;
import client.common.javascript.JsFunction2;
import client.common.javascript.JsProcedure1;
import client.common.javascript.JsProcedure2;
import client.common.javascript.JsWindow;

public class ProfesorScope extends NgScope {

	private JsWindow window;
	private UIState state;
	private Map<String, String> stateParams;
	private UserEP userEP;
	@SuppressWarnings("unused")
	private User user;
	protected String helpUrl;

	public ProfesorScope(UserEP userEP, UIState state,
			Map<String, String> stateParams, JsWindow window) {
		super("ProfesorScope");
		this.user = userEP.getMyInfo();
		this.userEP = userEP;
		this.state = state;
		this.stateParams = stateParams;
		this.window = window;

		final ProfesorScope that = this;
		$on("$stateChangeSuccess",
				new JsProcedure2<Object, Map<String, String>>() {

					@Override
					public void $invoke(Object t1, Map<String, String> state) {
						that.helpUrl = "api/help/" + state.$get("name");
					}
				});

	}

	public static Array<String> $inject() {
		return $array("User", "$state", "$stateParams", "$window");
	}

	public void logOut() {
		final ProfesorScope self = this;
		console.log(userEP.logout(new JsProcedure1<EmptyPromise>() {

			@Override
			public void $invoke(EmptyPromise p) {
				console.log("pasa por aqui");
				self.window.location.href = "/";
			}
		}));
	}

	public boolean isState(String sstate, Boolean params) {
		boolean b = state.includes(sstate);
		if (!!params) {
			final ProfesorScope self = this;
			b = b
					&& _.every(params,
							new JsFunction2<Boolean, Object, String>() {
								@Override
								public Boolean $invoke(Object v, String k) {
									return self.stateParams.$get(k) == v;
								}
							});
		}
		return b;
	}
}
